var _ = require('lodash'),
    Q = require('q'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    wareHouseController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
    deliveryRecordController = require('../../../ProduceWork/server/controllers/DeliveryRecord.server.controller'),
    Transaction = require('../../../Base/server/controllers/Transaction');

exports.getWareHouses = function (req, res) {
    wareHouseController.getAll().then(function (records) {
        res.json({
            Data: records,
            Error: null
        });
    }, function (err) {
        res.json({
            Data: null,
            Error: err
        });
    });
};

exports.getDeliveryRecords = function (req, res) {
    var wareHouse = req.body.WareHouse;
    deliveryRecordController.queryDeliveryRecords(wareHouse).then(function (records) {
        res.json({
            Data: records,
            Error: null
        });
    }, function (err) {
        res.json({
            Data: null,
            Error: err
        });
    });
};

exports.updateDeliveryStatus = function (req, res) {
    var deliveryIds = req.body.DeliveryIds,
        userId = req.body.UserId;
    var deliveryRecords = [], batches = [];
    _.forEach(deliveryIds, function (deliveryId) {
        batches.push(collectDeliveryRecord(deliveryId, userId, deliveryRecords));
    });
    Q.all(batches).then(function () {
        return Q.nfcall(Transaction.BatchSaveByTran, [{EntityName: 'DeliveryRecord', Records: deliveryRecords}]);
    }).then(function () {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    }).done();
};

function collectDeliveryRecord(deliveryId, userId, deliveryRecords) {
    var deferred = Q.defer();

    deliveryRecordController.queryByCondition({ _id: deliveryId}, function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询配送记录错误';
            newErr.message = '查询配送记录失败，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        if (records.length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询配送记录失败';
            newErr.message = '查询配送记录失败，未找到更新记录！';
            deferred.reject(newErr);
            return;
        }
        deliveryRecords.push({
            _id: records[0]._id,
            Status: 1,
            RowStatus: BaseEnum.RowStatus.Modify.Value,
            ModifyBy: userId,
            SysVersion: records[0].SysVersion
        });
        deferred.resolve();
    });

    return deferred.promise;
}
